<template>
    <el-dialog :draggable="true" :destroy-on-close="true" :model-value="checkDialog" @close="onCancel"
        :close-on-click-modal="false" title="新增服务项目" width="85%" top="8vh" class="check-dialog">
        <div class="table" >
            <el-table :border="true" stripe resizable height="450px" :data="tableDataList.feeDetails" :row-class-name="tableRowClassName" @cell-mouse-enter="onCellMouseEnter" @cell-mouse-leave="onCellMouseLeave">
                <el-table-column label="操作" width="70" type="index" fixed="left" align="center">
                    <template #default="scope">
                        <div v-show="styleColumn[scope.$index].tableColumnIndex" :rowIndex="scope.$index">
                            <span>{{ scope.$index +1 }}</span>
                        </div>
                        <div v-show="styleColumn[scope.$index].tableColumnBtn">
                            <span class="operation"> 
                                <el-icon @click="addItem" color="#007cff" size="16" class="icon">
                                <CirclePlus />
                            </el-icon>
                            <el-icon color="rgba(245, 108, 108, 1)" size="16" class="icon" @click="deleteItem(scope.$index)" v-show="tableDataList.feeDetails.length > 1">
                                <RemoveFilled />
                            </el-icon>
                        </span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="结算类型" width="150">
                    <template #default="scope">
                        <el-select placeholder="结算类型" v-model="scope.row.type" filterable clearable>
                            <el-option v-for="item in options1" :value="item.value" :key="item.value" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="费用项目" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <el-select placeholder="请选择" filterable clearable v-model="scope.row.workFeeProjectId"
                            :remote-method="getworkFeeProjectPageSelect" :loading="loading" remote remote-show-suffix>
                            <el-option v-for="item in modules" @click="changeworkFeeProjectId(item, scope.$index)"
                                :value="item.id" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip label="申请数量" width="100">
                    <template #default="scope">
                        <el-input @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
                            v-model="scope.row.qty" placeholder="数量" />
                    </template>
                </el-table-column>
                <el-table-column label="单价金额" width="120">
                    <template #default="scope">
                        <el-input  clearable v-model="scope.row.price"
                        @keyup="checkNum"    @input="scope.row.price = scope.row.price.replace(/[^\d.]/g,'')">
                            <template #prepend>￥</template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="总金额" width="120">
                    <template #default="scope">
                        <el-input disabled clearable :value="scope.row.price * scope.row.qty">
                            <template #prepend>￥</template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip label="备注" min-width="140" max-width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" clearable placeholder="填写备注" />
                    </template>
                </el-table-column>
                <el-table-column label="附件(最多上传8个)" width="460">
                    <template #default="scope">
                        <div class="updata_pic">
                            <el-upload action="#"
                                :limit="(8 - Number(scope.row.images.length)) == 0 ? -1 : (8 - Number(scope.row.images.length))"
                                multiple list-type="picture-card" accept="image/*,.pdf" :auto-upload="false"
                                :show-file-list="false" :on-change="(file) => { getProImages(file, scope.$index) }">
                                <div class="plus_add">
                                    <el-icon size="12">
                                        <Plus />
                                    </el-icon>
                                </div>
                            </el-upload>
                            <div class="disf_ipc" v-for="(img, index) in scope.row.images">
                                <img :src="pdf" alt="" style="width: 100%;cursor: pointer"
                                    v-if="(img.image.replace(/.+\./, '') == 'pdf') || img.file?.type.includes('pdf')">
                                <img class="img" :src="img.image" v-else />
                                <span class="item-actions">
                                    <el-icon color="#fff" size="12" class="item-preview"
                                        @click="handlePictureCardPreview(img.image)"><zoom-in /></el-icon>
                                    <el-icon size="12" color="#fff" class="item-delete"
                                        @click="handleRemove(index, scope.$index)">
                                        <Delete />
                                    </el-icon>
                                </span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="footer_remark">
            <el-form-item label="审核备注" label-width="auto">
                <el-input class="w_input" type="textarea" size="small" show-word-limit maxlength="200"
                    :autosize="{ minRows: 2, maxRows: 4 }" v-model="tableDataList.remark" clearable placeholder="填写备注信息" />
            </el-form-item>
        </div>
        <div class="btns flex-justify-end">
            <el-button color="#007cff" class="btn_save" @click="onSaveBtn">提交申请</el-button>
            <el-button @click="onCancel" class="btn_cancel"> 取消 </el-button>
        </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible" draggable title="查看附件" top="8vh"  width="70%">
        <iframe :src="`${dialogImageUrl}`" style="height: 660px;width: 100%;" frameborder="0"></iframe>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, toRefs, watch, reactive, onMounted } from 'vue'
import { feeSaveOrder, workFeeProjectPageSelect } from '../../../../../api/order'
import { orderAnnexUpload } from '../../../../../api/upload'
import pdf from '@/assets/image/pdf.png'
import { ElMessage, ElMessageBox } from 'element-plus'
import {checkNum} from '../../../../../utils/validate'
const props = defineProps({
    checkDialog: Boolean,
    workId: [String, Array]
})
const { checkDialog, workId } = toRefs(props)
const dialogVisible = ref(false)
const dialogImageUrl = ref(null)
const modules = ref(null)
const loading = ref(false)
const emits = defineEmits(['assign-dialog', 'update-list'])
const styleColumn = ref([{
    tableColumnBtn: false,
    tableColumnIndex: true,
}])
// 结算类型
const options1 = [{ name: '向服务商收取', value: 1 }, { name: '向服务商支付', value: 2 }, { name: '向客户收取', value: 3 }, { name: '向客户支付', value: 4 }]

const tableDataList = reactive({
    id: null,//服务费用项目ID
    workId: null,//工单ID
    remark: "",//	审核备注
    feeDetails: [
        {
            "delImageIds": [],//删除的工单费用图片对象ID	
            "id": null,//	费用项目详情ID，新增不必传，修改必传
            "images": [],
            "price": 0,//费用金额
            "qty": 1,//数量
            updatePrice: false,
            "remark": "",//备注
            "status": 1, //审核状态 1-待审核，2-已通过，3-已驳回
            "type": 1,//结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
            "workFeeProjectId": null,//工单费用项目ID	
        }
    ]    
})

// 给row对象赋索引值，注：在此赋值后，才可以在其他用到row的地址取值
const tableRowClassName = ({row, rowIndex}) => {
    row.index = rowIndex
}
// 鼠标移入事件
const onCellMouseEnter = (row, column, cell, event, index) => {
    styleColumn.value[row.index].tableColumnBtn = true
    styleColumn.value[row.index].tableColumnIndex = false
}
// 鼠标移出事件
const onCellMouseLeave = (row, column, cell, event, index) => {
    styleColumn.value[row.index].tableColumnBtn = false
    styleColumn.value[row.index].tableColumnIndex = true
}


// 添加
function addItem() {
    let item = {
        "delImageIds": [],//删除的工单费用图片对象ID	
        "id": null,//	费用项目详情ID，新增不必传，修改必传
        "images": [],
        "price": 0,//费用金额
        "qty": 1,//数量
        updatePrice: false,
        "remark": "",//备注
        "status": 1,//审核状态 1-待审核，2-已通过，3-已驳回
        "type": 1,//结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
        "workFeeProjectId": null,//工单费用项目ID	
    }
    tableDataList.feeDetails.push(item)
    styleColumn.value.push({
        tableColumnIndex: true,
        tableColumnBtn: false
    })
}
// 新增删除
function deleteItem(n: number) {
    if (tableDataList.feeDetails.length == 1) {
        return
    }
    tableDataList.feeDetails = tableDataList.feeDetails.filter((o, index) => {
        return index != n
    })
    styleColumn.value.splice(n, 1)
}
// 保存
async function onSaveBtn() {
    for (const key in tableDataList.feeDetails) {
        let imgobj = tableDataList.feeDetails[key];
        let arrimg = []
        if (imgobj.images.length > 0) {
            for (const i in imgobj.images) {
                arrimg.push(imgobj.images[i].file)
            }
            if (imgobj.images[0].file) {
                await orderAnnexUpload(arrimg).then(res => {
                    imgobj.images = res.data.data.rows.map(o => ({ id: null, image: o }))
                })
            }
        }
    }
    tableDataList.workId = workId.value
    feeSaveOrder(tableDataList).then(res => {
        if (res.data.success) {
            ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'success',
                offset: 200,
            })
            emits('update-list')
            onCancel()
        } else {
            ElMessage({
                showClose: true,
                message: res.data.message,
                duration: 4000,
                offset: 200,
                type: 'error'
            })
        }
    })

}
// 费用项目选择变化
function changeworkFeeProjectId(item, index) {
    tableDataList.feeDetails[index].price = item.price
    tableDataList.feeDetails[index].updatePrice = item.updatePrice
}
// 费用项目下拉数据
async function getworkFeeProjectPageSelect(val) {
    loading.value = true
    let data = {
        "limit": 0,
        "name": val,
        "page": 0
    }
    await workFeeProjectPageSelect(data).then(res => {
        if (res.data.success) {
            modules.value = res.data.data.rows
        } else {
            ElMessage({
                showClose: true,
                message: res.data.message,
                duration: 4000,
                offset: 200,
                type: 'error'
            })
        }
        loading.value = false
    })
}
// 删除图片
const handleRemove = (imgindex, index) => {
    tableDataList.feeDetails[index].images = tableDataList.feeDetails[index].images.filter((o, i) => i != imgindex)
}
// 查看图片
const handlePictureCardPreview = (img) => {
    dialogImageUrl.value = img
    dialogVisible.value = true
}
// 添加图片
const getProImages = async (img, index) => {
    tableDataList.feeDetails[index].images.push({ image: img.url, file: img.raw })
}

const onCancel = () => {
    emits('assign-dialog')
}
onMounted(() => {
    getworkFeeProjectPageSelect('')
})
</script>

<style lang="scss" scoped>

.top_no {
    padding-bottom: 8px;
    font-size: 12px;
    color: #999;
}

.operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
        cursor: pointer;
        margin: 0 6px;

        &:hover {
            transform: scale(1.2);
        }
    }
}

:deep(.el-table td.el-table__cell) {
    .el-input {
        .el-input__wrapper {
            height: 28px;
        }

        .el-input-group__prepend {
            padding: 0 2px;
        }
    }
}

.btn_save {
    width: 60px;
}

.btn_cancel {
    width: 60px;

    &:hover {
        border: 1px solid #e5e5e5;
        color: #999;
        background-color: #e5e5e5;
    }
}

.footer_remark {
    margin-top: 20px;

    .w_input {
        width: 600px;
        margin-left: 10px;
    }
}

:deep(.updata_pic) {
    display: flex;
    align-items: center;

    .el-upload {
        &.el-upload--picture-card {
            width: 40px;
            height: 40px;
        }
    }

    .disf_ipc {
        display: flex;
        width: 40px;
        height: 40px;
        position: relative;
        margin-left: 6px;
        border: 1px solid #7f7f7f27;
        border-radius: 2px;
        box-sizing: border-box;
        overflow: hidden;

        .img {
            width: 100%;
            position: absolute;
            border-radius: 2px;
        }

        .item-actions {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0;
        }

        &:hover .item-actions {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #7f7f7f9d;
            opacity: 1;
            border-radius: 2px;

            .item-preview {
                margin: 0 4px;
                cursor: pointer;

                &:hover {
                    transform: scale(1.2);
                }
            }

            .item-delete {
                margin: 0 4px;
                cursor: pointer;

                &:hover {
                    transform: scale(1.2);
                }
            }
        }
    }
}
</style>